package com.c.ctgproject.ui.collect

import android.content.Intent
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.adapter.HandlerBatteryAdapter
import com.c.ctgproject.adapter.PhotoShowListAdapter
import com.c.ctgproject.base.BaseActivityV2
import com.c.ctgproject.databinding.ActivityHandlerBatteryV2Binding
import com.c.ctgproject.entity.HandlerBatteryEntity
import com.c.ctgproject.entity.file.CommonFileResultEntity
import com.c.ctgproject.enum.DictionaryMenuEnum
import com.c.ctgproject.event.CarListBatteryOilEvent
import com.c.ctgproject.http.ApiMethods
import com.c.ctgproject.http.MyObserverHandlerLoading
import com.c.ctgproject.utils.*
import com.google.gson.JsonArray
import com.lwkandroid.imagepicker.ImagePicker
import com.lwkandroid.imagepicker.data.ImageBean
import com.lwkandroid.widget.ninegridview.NineGridBean
import kotlinx.android.synthetic.main.activity_handler_battery_v2.*
import kotlinx.coroutines.*
import org.greenrobot.eventbus.EventBus
import java.io.File

class HandlerBatteryV2Activity : BaseActivityV2(), PhotoShowListAdapter.DeleteCallBack ,HandlerBatteryAdapter.CarPartHandlerAdapterListener{
    private val mBinding by lazy { ActivityHandlerBatteryV2Binding.inflate(layoutInflater) }
    private val mViewModel by lazy { ViewModelProvider(this)[HandlerBatteryViewModel::class.java] }
    override fun getLayout() = mBinding.root
    private val mCarId by lazy { intent.getIntExtra(MyConstants.CAR_ID, -1).handlerNull() }

    //有无电池
    private var hasBattery = false

    //是否直接拆解完成
    private var handlerFinish = false
    private var batteryName = ""


    private val imageShowList = ArrayList<String>()
    private val imageResultCode = 100
    private val mListPosition by lazy { intent.getIntExtra(MyConstants.POSITION, -1) }
    private val mList = ArrayList<HandlerBatteryEntity>()
    private val mAdapter by lazy { HandlerBatteryAdapter(this, mList, mViewModel, this,this) }
    override fun event() {
        val handlerBatteryEntity = HandlerBatteryEntity()
        mList.add(handlerBatteryEntity)
        //AndroidBug5497Workaround.assistActivity(this)
        mBinding.mRecyclerView.layoutManager = LinearLayoutManager(this)
        mBinding.mRecyclerView.adapter = mAdapter
        mBinding.mPhotoNGV.init(this, imageShowList, 6, imageResultCode)
        //进页面默认无电池 先不展示
        mBinding.mLayout.gone()
        mBinding.mImageSelect.gone()
        mBinding.stockNumStart.gone()
        mBinding.moduleCountLL.gone()
        mBinding.moduleCountLine.gone()
        mBinding.mHandlerFinishRG.gone()
    }

    //    private var enterMode=1
    override fun click() {
        mBinding.mAddBatteryBtn.setOnClickListener {
            if(mList.size<2){
                mList.add(HandlerBatteryEntity())
                mAdapter.notifyDataSetChanged()
            }else{
                showToast("最多拆解两个电池")
            }
            if(mList.size==2){
                mBinding.mAddBatteryBtn.visibility=View.GONE
            }else{
                mBinding.mAddBatteryBtn.visibility=View.VISIBLE
            }
        }
        mBinding.voltage.handlerDecimal3 {
            val result = handlerKwh(it, mBinding.capacityAh.text.handlerNull())
            result?.let {
                mBinding.capacityKWh.textSet(result)
            }
        }
        mBinding.capacityAh.handlerDecimal3 {
            val result = handlerKwh(it, mBinding.voltage.text.handlerNull())
            result?.let {
                mBinding.capacityKWh.textSet(result)
            }
        }
        mBinding.capacityKWh.handlerDecimal3()

        //选择电池名称
        mBinding.mDictionarySelectLL.setOnClickListener {
            DictionaryMenuActivity.jumpToDictionary(this, DictionaryMenuEnum.BATTERY.menuCode, true, arrayListOf(batteryName))
        }

        //是否直接拆解完成
        mBinding.mCHAIY.setOnClickListener {
            handlerFinish = true
            mViewModel.setFinish(true)
            mAdapter.notifyDataSetChanged()
        }
        mBinding.mCHAIN.setOnClickListener {
            handlerFinish = false

            mViewModel.setFinish(false)
            mAdapter.notifyDataSetChanged()
        }
        mBinding.mYDC.setOnClickListener {
            hasBattery = true
            mRecyclerLL.visibility = View.VISIBLE
            mBinding.mHandlerFinishRG.visible()

        }
        mBinding.mWDC.setOnClickListener {
            hasBattery = false
            mRecyclerLL.visibility = View.GONE
            mBinding.mHandlerFinishRG.gone()

        }

//        mBinding.mCJ.setOnClickListener {
//            enterMode=1
//        }
//        mBinding.mSJ.setOnClickListener {
//            enterMode=2
//        }

        mBinding.mConfirmBTN.setOnClickListener {
            if (!hasBattery) {
                //没电池直接走接口
                val map = HashMap<String, Any>()
                val pushData=JsonArray()
                val handlerBatteryEntity = HandlerBatteryEntity()
                handlerBatteryEntity.carId= mCarId
                pushData.add(getGson().toJsonTree(handlerBatteryEntity))
                ApiMethods.apiSubscribe(ApiMethods.retrofit.handlerBattery(handlerBodyEntity(pushData)), MyObserverHandlerLoading(this, loading) {
                    MyLog.d("无电池拆解电池完成回调:$it")
                    showToast("提交成功")
                    val event = CarListBatteryOilEvent()
                    event.position = mListPosition
                    event.battery = true
                    EventBus.getDefault().post(event)
                    finish()
                })
            } else {
                for (i in 0 until mList.size) {
                    val data = mList[i]
                    if (hasBattery && data.batteryName.isNullOrEmpty()) {
                        showToast("电池${i + 1}请选择电池名称")
                        return@setOnClickListener
                    } else if (handlerFinish &&( data.count == null||data.count == 0)) {
                        showToast("电池${i + 1}请输入数量")
                        return@setOnClickListener
                    } else if (handlerFinish &&( data.moduleCount == null|| data.moduleCount == 0)) {
                        showToast("电池${i + 1}请输入模组个数")
                        return@setOnClickListener
                    }else if (handlerFinish &&( data.bulkInOrderNo.isNullOrEmpty())) {
                        showToast("电池${i + 1}请输入入库编码")
                        return@setOnClickListener
                    }
//                    else if(handlerFinish  &&( data.stockPosi == null)){
//                        showToast("电池${i + 1}请输入库位")
//                        return@setOnClickListener
//                    }
                    else {
                        if (data.picUrls.isEmpty()) {
                            showToast("电池${i + 1}请添加照片")
                            return@setOnClickListener
                        } else {

                        }

                    }
                }
                handlerHttp()
            }
        }
    }

    private fun handlerHttp() {
        val jsonPush = JsonArray()


        mList.forEach { entity ->

            entity.carId = mCarId
            if (mViewModel.isFinish.value==true) {
                entity.dismantled = 1
            } else {
                entity.moduleCount = null
                entity.dismantled = 0
            }
            jsonPush.add(getGson().toJsonTree(entity))
        }
        MyLog.d("测试数据${getGson().toJson(jsonPush)}")
        ApiMethods.apiSubscribe(ApiMethods.retrofit.handlerBattery(handlerBodyEntity(jsonPush)), MyObserverHandlerLoading(this, loading) {
            MyLog.d("拆解电池完成回调:$it")
            showToast("提交成功")
            val event = CarListBatteryOilEvent()
            event.position = mListPosition
            event.battery = true
            EventBus.getDefault().post(event)
            finish()
        })

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        data?.let { result ->
            when (requestCode) {
                1000 -> {
                    //字典回调
                    val name = result.getStringExtra(MyConstants.NAME)
                    val position = data.getIntExtra(MyConstants.POSITION, -1)
                    if (position != -1) {
                        mList[position].batteryName = name
                        mAdapter.notifyDataSetChanged()
                    }

//                val abbreviation=result.getStringExtra(MyConstants.ABBREVIATION)
                    batteryName = name.handlerNull()
                    mBinding.stockName.text = name.handlerNull()
                }
                imageResultCode -> {
                    MyLog.d("图片图片1")
                    val list: List<ImageBean>? = result.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
                    val resultList: MutableList<NineGridBean> = ArrayList()
                    list?.forEach { imageBean ->
                        val nineGirdData = NineGridBean(imageBean.imagePath)
                        imageShowList.add(imageBean.imagePath)
                        resultList.add(nineGirdData)
                    }

                    mBinding.mPhotoNGV.addDataList(resultList)
                }
                else -> {
                    if (requestCode < 100) {
                        MyLog.d("图片图片2")
                        val list: List<ImageBean>? = result.getParcelableArrayListExtra(ImagePicker.INTENT_RESULT_DATA)
                        val fileList = ArrayList<File>()
                        var index = 0
                        list?.forEach {
                            it?.let {
                                index++
                                val file = File(it.imagePath)
                                val newFile: File = WaterRemark.handlerWaterRemark2File(this, file, index.toString())
                                fileList.add(newFile)
                            }

                        }


                        upDataFile(fileList) {

                            it?.forEach { b ->
                                mList[requestCode].picUrls.add(b.fileUrl.handlerNull())
                            }
                            mAdapter.notifyItemChanged(requestCode)
                        }
                    }
                }
            }
        }
    }

    override fun deleteItem(url: String, position: Int) {

    }

    override fun onBatteryDelete() {
        if(mList.size==2){
            mBinding.mAddBatteryBtn.visibility=View.GONE
        }else{
            mBinding.mAddBatteryBtn.visibility=View.VISIBLE
        }
    }

}